package com.bsoft.gol.hcs.specialist.service.impl;

import com.alibaba.fastjson.JSON;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpStatisticExcelUtil;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.mvc.upload.FileMetaEntity;
import ctd.mvc.upload.FileService;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.base.Organization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import service.rpc.IBBPService;
import service.rpc.IOrganizationRpcService;
import com.bsoft.gol.hcs.specialist.bean.request.DiseaseFollowUpStatisticsReq;
import com.bsoft.gol.hcs.specialist.bean.request.StatisticsRecordRequest;
import com.bsoft.gol.hcs.specialist.bean.request.WorkloadStatisticsReq;
import com.bsoft.gol.hcs.specialist.bean.response.DiseaseFollowUpStatisticsResp;
import com.bsoft.gol.hcs.specialist.bean.response.StatisticsRecord;
import com.bsoft.gol.hcs.specialist.bean.response.StatisticsRecordResponse;
import com.bsoft.gol.hcs.specialist.bean.response.WorkloadStatisticsResp;
import com.bsoft.gol.hcs.specialist.dao.FollowUpRecordsDAO;
import com.bsoft.gol.hcs.specialist.dao.FusTeamChronicGroupRecordDAO;
import com.bsoft.gol.hcs.specialist.service.IFollowUpStatisticsService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import org.atag.dao.model.PageInfo;

import java.io.ByteArrayInputStream;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author lixy
 * @date 2021/12/3 8:31
 */
@SsdevService("followUpStatisticsService")
public class FollowUpStatisticsServiceImpl implements IFollowUpStatisticsService {

    protected static final Logger log = LoggerFactory.getLogger(FollowUpStatisticsServiceImpl.class);

    public FollowUpStatisticsServiceImpl() {
    }

    @Autowired
    private FollowUpRecordsDAO followUpRecordsDAO;

    @Autowired
    private FusTeamChronicGroupRecordDAO fusTeamChronicGroupRecordDAO;
    @Autowired
    private IBBPService bbpService;
    @Autowired
    private IOrganizationRpcService organizationRpcService;


    /**
     * 统计入组、随访人次
     *
     * @param statisticsRecordRequest req
     * @return list
     */
    @Override
    @RpcService
    public List<StatisticsRecordResponse> statisticsRecord(StatisticsRecordRequest statisticsRecordRequest) {

        // 按照 科室、病种组查询 科室 机构名称 病种 历史入组人次 新增入组人次 当前在组人数
        List<StatisticsRecordResponse> responseList = followUpRecordsDAO.statisticsRecord(statisticsRecordRequest);

        // 按照 科室、病种组查询 历史随访人次 历史随访成功率
        List<StatisticsRecord> statisticsRecords = followUpRecordsDAO.statisticsFollowRecord(statisticsRecordRequest);

        log.info(JSON.toJSONString(statisticsRecords));

        if (CommonUtils.isNotEmpty(responseList)) {

            int totalHistoryNumber = 0;
            int totalNewNumber = 0;
            int totalCurrentNumber = 0;
            int totalHistoryFollowUpNumber = 0;
            int totalSucFollowUpNumber = 0;

            Set<String> totalDept = new HashSet<>();
            Set<String> totalOrg = new HashSet<>();

            for (StatisticsRecordResponse statisticsRecordResponse : responseList) {

                boolean flag = true;
                if (CommonUtils.isNotEmpty(statisticsRecords)) {
                    for (StatisticsRecord statisticsRecord : statisticsRecords) {

                        if (statisticsRecordResponse.getChronicDiseaseId().equals(statisticsRecord.getDiseaseTypeId())) {
                            statisticsRecordResponse.setHistoryFollowUpNumber(statisticsRecord.getHistoryFollowUpNumber());
                            statisticsRecordResponse.setHistoryFollowUpRate(statisticsRecord.getHistoryFollowUpRate());
                            statisticsRecordResponse.setSucFollowUpNumber(statisticsRecord.getSucFollowUpNumber());
                            flag = false;
                            break;
                        }
                    }
                }

                if (flag) {
                    statisticsRecordResponse.setHistoryFollowUpNumber("0");
                    statisticsRecordResponse.setHistoryFollowUpRate("0");
                }
                totalOrg.add(statisticsRecordResponse.getOrganizationName());
                totalDept.add(statisticsRecordResponse.getDepartmentName());
                totalHistoryNumber += Integer.parseInt(statisticsRecordResponse.getHistoryNumber());
                totalNewNumber += Integer.parseInt(statisticsRecordResponse.getNewNumber());
                totalCurrentNumber += Integer.parseInt(statisticsRecordResponse.getCurrentNumber());
                if (CommonUtils.isNotEmpty(statisticsRecordResponse.getHistoryFollowUpNumber())) {
                    totalHistoryFollowUpNumber += Integer.parseInt(statisticsRecordResponse.getHistoryFollowUpNumber());
                }
                if (CommonUtils.isNotEmpty(statisticsRecordResponse.getSucFollowUpNumber())) {
                    totalSucFollowUpNumber += Integer.parseInt(statisticsRecordResponse.getSucFollowUpNumber());

                }
            }

            StatisticsRecordResponse statisticsRecordResponse = new StatisticsRecordResponse();

            statisticsRecordResponse.setOrganizationName("机构总数 " + totalOrg.size());
            statisticsRecordResponse.setDepartmentName("科室总数 " + totalDept.size());
            statisticsRecordResponse.setChronicDiseaseName("病种总数 " + responseList.size());
            statisticsRecordResponse.setHistoryNumber(totalHistoryNumber + "");
            statisticsRecordResponse.setNewNumber(totalNewNumber + "");
            statisticsRecordResponse.setCurrentNumber(totalCurrentNumber + "");
            statisticsRecordResponse.setHistoryFollowUpNumber(totalHistoryFollowUpNumber + "");
            DecimalFormat decimalFormat = new DecimalFormat("0.00");

            if (totalHistoryFollowUpNumber == 0) {
                statisticsRecordResponse.setHistoryFollowUpRate("0%");
            }else {
                String divide = decimalFormat.format((float) totalSucFollowUpNumber / (float) totalHistoryFollowUpNumber);
                statisticsRecordResponse.setHistoryFollowUpRate(divide + "%");
            }
            responseList.add(statisticsRecordResponse);
        }
        return responseList;
    }

    /*随访工作量统计*/
    @Override
    @RpcService
    public PageInfo<WorkloadStatisticsResp> workloadStatistics(WorkloadStatisticsReq workloadStatisticsReq) {
        PageInfo<WorkloadStatisticsResp> pageInfo = new PageInfo();
        //获取总条数
        Long total01 = followUpRecordsDAO.getCountByFollowUpRecordsForWorkloadStatistics(workloadStatisticsReq).longValue();
        Long total02 = fusTeamChronicGroupRecordDAO.getCountByFusTeamChronicGroupRecordForWorkloadStatistics(workloadStatisticsReq).longValue();
        pageInfo.setTotal(total01 > total02 ? total01 : total02);
        pageInfo.setPageNum(workloadStatisticsReq.getPageNo());
        pageInfo.setPageSize(workloadStatisticsReq.getPageSize());
        List<WorkloadStatisticsResp> workloadStatisticsRespList = new ArrayList<>();
        int startRow = (workloadStatisticsReq.getPageNo() - 1) * workloadStatisticsReq.getPageSize();
        workloadStatisticsReq.setPageNo(startRow);
        workloadStatisticsRespList = followUpRecordsDAO.workloadStatisticsRespList(workloadStatisticsReq);
        if (CommonUtils.isNotEmpty(workloadStatisticsRespList)) {
            Organization organization = organizationRpcService.getOrgDetailByOrgCode(workloadStatisticsReq.getOrganizationId());
            Map<String, String> cdMap = null;
            if (null != organization) {
                cdMap = bbpService.getCdMap(organization.getOrgId());
            }
            Map<String, String> finalCdMap = cdMap;

            workloadStatisticsRespList.forEach(v -> {
                //医生工号
                String cd = "";
                //医生工号修改，由于查出来的doctorId是医生代码，不是医生工号，所以要去bbp那边查询医生工号
                if (null != organization && CommonUtils.isNotEmpty(v.getDocCode())) {
                    cd = bbpService.getCdString(finalCdMap, organization.getOrgId(), v.getDocCode());
                    v.setDocCode(cd);
                }
            });
            WorkloadStatisticsResp workloadStatisticsRespTotal = followUpRecordsDAO.workloadStatisticsTotal(workloadStatisticsReq);
            workloadStatisticsRespList.add(workloadStatisticsRespTotal);
            pageInfo.setList(workloadStatisticsRespList);
        }
        return pageInfo;
    }

    /*病种随访统计*/
    @Override
    @RpcService
    public PageInfo<DiseaseFollowUpStatisticsResp> diseaseFollowUpStatistics(DiseaseFollowUpStatisticsReq diseaseFollowUpStatisticsReq) {
        PageInfo<DiseaseFollowUpStatisticsResp> pageInfo=new PageInfo();
        //获取总条数
        Long total01= followUpRecordsDAO.getCountByFollowUpRecords(diseaseFollowUpStatisticsReq).longValue();
        Long total02= fusTeamChronicGroupRecordDAO.getCountByFusTeamChronicGroupRecord(diseaseFollowUpStatisticsReq).longValue();
        pageInfo.setTotal(total01>total02?total01:total02);
        pageInfo.setPageNum(diseaseFollowUpStatisticsReq.getPageNo());
        pageInfo.setPageSize(diseaseFollowUpStatisticsReq.getPageSize());
        List<DiseaseFollowUpStatisticsResp> diseaseFollowUpStatisticsRespList=new ArrayList<>();
        int startRow=(diseaseFollowUpStatisticsReq.getPageNo()-1)*diseaseFollowUpStatisticsReq.getPageSize();
        diseaseFollowUpStatisticsReq.setPageNo(startRow);
        diseaseFollowUpStatisticsRespList= followUpRecordsDAO.diseaseFollowUpStatistics(diseaseFollowUpStatisticsReq);
        pageInfo.setList(diseaseFollowUpStatisticsRespList);
        return pageInfo;
    }

    /**
     * 病种随访统计excel导出
     * @param req
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public String diseaseFollowUpStatisticsExport(DiseaseFollowUpStatisticsReq req) throws ControllerException {
        PageInfo<DiseaseFollowUpStatisticsResp> diseaseFollowUpStatisticsRespPageInfo = diseaseFollowUpStatistics(req);
        byte[] data = FollowUpStatisticExcelUtil.getExcelAsByteArrayForDiseaseFollowUpStatistics(req,diseaseFollowUpStatisticsRespPageInfo.getList());
        return uploadExcel(data, "病种随访统计表.xlsx");
    }


    /**
     * 随访工作量统计excel导出
     * @param req
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public String workloadStatisticsExport(WorkloadStatisticsReq req) throws ControllerException {
        PageInfo<WorkloadStatisticsResp> workloadStatisticsRespPageInfo = workloadStatistics(req);
        byte[] data = FollowUpStatisticExcelUtil.getExcelAsByteArrayForWorkloadStatistics(req,workloadStatisticsRespPageInfo.getList());
        return uploadExcel(data, "随访工作量统计表.xlsx");
    }


    private String uploadExcel(byte[] bytes, String fileName){
        int filesize = bytes.length;
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        UserRoleToken token = UserRoleToken.getCurrent();
        FileMetaEntity fileMeta = new FileMetaEntity();
        fileMeta.setLastModify(new Date());
        fileMeta.setUploadTime(new Date());
        fileMeta.setMode(31);
        fileMeta.setFileName(fileName);
        fileMeta.setContentType("application/octet-stream");
        fileMeta.setOwner(token.getUserId());
        fileMeta.setFileSize(filesize);
        fileMeta.setCatalog("export-file");
        String fileId = null;
        try {
            fileId = FileService.instance().upload(fileMeta, bis);
        } catch (Exception e) {
            log.error("文件上传失败", e);
        }
        return fileId;
    }
}
